package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.core.listener.DictExcelVoListener;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.entity.vo.DictExcelVo;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2024-10-11
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    DictExcelVoListener dictExcelVoListener;

    @Resource
    RedisTemplate redisTemplate;


    @Override
    public void importExcel(MultipartFile file) {
        //校验文件格式和数据是否为空
        if (!(file.getOriginalFilename().endsWith(".xls")||file.getOriginalFilename().endsWith(".xlsx"))){
            throw new SrbException(ResponseEnum.FILE_FORM_ERROR);
        }

        if (file.getSize()==0){
            throw new SrbException(ResponseEnum.DATA_NOT_NULL_ERROR);
        }

        try {
            EasyExcel.read(file.getInputStream())
                    .head(DictExcelVo.class)
                    .sheet()
                    .registerReadListener(dictExcelVoListener)
                    .doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SrbException(ResponseEnum.IMPORT_DATA_ERROR);
        }
    }
    /*
        1、缓存管理注解：EnableCaching(启用缓存管理)、Cachable(判断如果没有则设置缓存)、CachePut(保存缓存)
                        CacheEvict(删除缓存)
           步骤：1、启用缓存管理@EnableCaching 2、创建缓存管理器(配置缓存方式) 3、在需要缓存的业务方法上添加注解
                4、更新世数据可以上缓存失效
     */
    @Cacheable(value = "srb:dicts",key = "#pid")
    @Override
    public List<Dict> parent(Long pid) {
        //1、先查询缓存：如果存在直接返回
//        List<Dict> dicts = (List<Dict>) redisTemplate.opsForValue().get("srb:dicts"+pid);
//        if (!CollectionUtils.isEmpty(dicts)){
//            return dicts;
//        }
        //2、redis中没有缓存：查询数据
        //先查询所有的一级数据字典集合
        List<Dict> dicts = this.list(Wrappers.lambdaQuery(Dict.class)
                .eq(Dict::getParentId,pid));
        if (CollectionUtils.isEmpty(dicts)){
            return null;
        }
        //查询每个一级字典是否有下一级
        dicts.forEach(dict -> {
            boolean flag = hasChildren(dict.getId());
            dict.setHasChildren(flag);
        });
        //存到redis中：每个pid的下一级数据字典分开缓存
        //redisTemplate.opsForValue().set("srb:dicts:"+pid,dicts);

        return dicts;
    }

    public boolean hasChildren(Long id) {
        boolean flag = this.count(Wrappers.lambdaQuery(Dict.class)
                .eq(Dict::getParentId, id))>0;
        return flag;
    }

    @CacheEvict(value = "srb:dicts",key = "#dict.parentId")//让redis中为dict.parentId的缓存失效
    @Override
    public void saveChildDict(Dict dict) {
        this.save(dict);
    }

    @Cacheable(value = "dict:cache:",key = "#dictCode")
    @Override
    public List<Dict> getByDictCode(String dictCode) {
        return baseMapper.getByDictCode(dictCode);
    }

    @Cacheable(value = "dict:cache:name:",key = "#dictCode+':'+#value")
    @Override
    public String getDictNameByDictCodeAndValue(String dictCode, Integer value) {
        return baseMapper.getDictNameByDictCodeAndValue(dictCode,value);
    }
}
